import Request from '@/utils/luch-request/index.js'

const getTokenStorage = () => {
  let token = ''
  try {
    token = uni.getStorageSync('tokenId')
  } catch (e) {
    //TODO handle the exception
  }
  return token
}

const getUserStorage = () => {
  let userId = ''
  try {
    let userInfo = uni.getStorageSync('userInfo');
	if(userInfo){
		userId = userInfo.id;
	}
  } catch (e) {
    //TODO handle the exception
  }
  return userId
}

const http = new Request();

http.setConfig((config) => { /* 设置全局配置 */
	config.version = 'V 1.1.0';
	config.timeout = 200000;
   if (process.env.NODE_ENV === 'production'){
	config.baseURL='https://jwzl.deepsiri.cn/jwzl/rest';
	config.uploadPath='https://jwzl.deepsiri.cn/jwzl-files';
  }else{
	config.baseURL='http://localhost:9080/jwzlDev/rest';
  	config.uploadPath='https://jwzl.deepsiri.cn/jwzl-files';
  }
	/* config.baseURL='https://jwzl.deepsiri.cn/jwzl/rest';
	config.uploadPath='https://jwzl.deepsiri.cn/jwzl-files'; */
  return config
})

http.interceptors.request.use((config) => { /* 请求之前拦截器。可以使用async await 做异步操作 */
	if(config.url.indexOf('/login')>0){		//登录不判断token
		
	}
	if (config.url.indexOf('/login')<0&&(!getTokenStorage()||!getUserStorage())) { // 如果token不存在，return Promise.reject(config) 会取消本次请求
		uni.showToast({
			icon:'none',
			title:'用户身份验证失败，请重新登录!'
		})
		uni.reLaunch({
			url: '/pages/login/login'
		});
	   return Promise.reject(config)
	}
	config.header = {
		tokenId: getTokenStorage(),
		userId: getUserStorage(),
		isApp: 'true'
	}
  return config
}, (config) => {
  return Promise.reject(config)
})

http.interceptors.response.use(async (response) => { 
	if (response.data.code === '101' || response.data.code==='301' || response.data.code === '402') {
		uni.reLaunch({
		    url: '/pages/login/login'
		});
	}
  return response
}, (response) => { 
	if (response.data.code === '101' || response.data.code==='301' || response.data.code === '402') {
		uni.reLaunch({
		    url: '/pages/login/login'
		});
		return Promise.reject(response);
	}
	if(response.statusCode >= 400){
		uni.showToast({
			icon:'none',
			title:'服务器出故障了!'
		})
		return Promise.reject(response);
	}
	console.log("请求失败");

  return Promise.reject(response)
})

export {
  http
}
